﻿using System.Collections.Generic;
using System.Linq;
using StockFinder.Model;
using StockFinder.Model.Constants;

namespace StockFinder.Indicators.Day.ClosePrice
{
    /// <summary>
    /// Generates the simple moving average value for the lookback period
    /// DailyPrice.DayIndicators[IndicatorName]
    /// </summary>
    public class SimpleMovingAverageClosePriceDayIndicator : BaseDayIndicator
    {
        public SimpleMovingAverageClosePriceDayIndicator(int lookbackPeriod, string indicatorName) 
            : base(lookbackPeriod, indicatorName)
        {}

        public override void ApplyIndicator(List<DailyPrice> prices)
        {
            if (!Initialize(prices)) return;

            var orderedPrices = prices.OrderBy(p => p.PriceDate);
            DailyPrice currentPrice;

            var pricesArray = orderedPrices.ToArray();
            IEnumerable<DailyPrice> skippedPrices;
            IEnumerable<DailyPrice> takenPrices;

            var pricesCount = orderedPrices.Count();            

            //start from lookback period
            for (var i = (LookbackPeriod - 1); i < pricesCount; i++)
            {
                currentPrice = pricesArray[i];

                var numberToSkip = (i + 1) - LookbackPeriod;

                skippedPrices = pricesArray.Skip(numberToSkip);

                takenPrices = skippedPrices.Take(LookbackPeriod);

                currentPrice.DayIndicators[IndicatorName] = takenPrices.Average(p => p.AdjustedClose);
            }
        }

        #region Common indicators
        public static readonly SimpleMovingAverageClosePriceDayIndicator _10 = new SimpleMovingAverageClosePriceDayIndicator(10, DayIndicatorNames.CLOSE_SMA10);
        public static readonly SimpleMovingAverageClosePriceDayIndicator _20 = new SimpleMovingAverageClosePriceDayIndicator(20, DayIndicatorNames.CLOSE_SMA20);
        public static readonly SimpleMovingAverageClosePriceDayIndicator Fifty = new SimpleMovingAverageClosePriceDayIndicator(50, DayIndicatorNames.CLOSE_SMA50);
        public static readonly SimpleMovingAverageClosePriceDayIndicator _200 = new SimpleMovingAverageClosePriceDayIndicator(200, DayIndicatorNames.CLOSE_SMA200);
        #endregion
    }
}
